package com.autumn.platform.web.resulthandler.wrapper.impl;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import com.autumn.platform.web.resulthandler.wrapper.ResultWrapper;

public class ResultWrapperComposite implements ResultWrapper, InitializingBean {

    @Autowired(required = false)
    private List<ResultWrapper> wrappers;

    @Override
    public boolean supports(Object result, MethodParameter returnType) {
        List<ResultWrapper> wrappers = getWrappers();
        if (null != wrappers) {
            for (ResultWrapper wrapper : wrappers) {
                if (wrapper.supports(result, returnType)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Object wrap(Object result, MethodParameter returnType) {
        List<ResultWrapper> wrappers = getWrappers();
        if (null != wrappers) {
            for (ResultWrapper wrapper : wrappers) {
                if (wrapper.supports(result, returnType)) {
                    return wrapper.wrap(result, returnType);
                }
            }
        }
        return result;
    }

    public List<ResultWrapper> getWrappers() {
        return wrappers;
    }

    public void setWrappers(List<ResultWrapper> wrappers) {
        this.wrappers = wrappers;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (null != this.wrappers) {
            AnnotationAwareOrderComparator.sort(this.wrappers);
        }
    }
}
